package com.powernode.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.constant.AuthConstant;
import com.powernode.domain.SysLoginUser;
import com.powernode.mapper.SysLoginUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class PowerUserDetailsService implements UserDetailsService {
    @Autowired
    private SysLoginUserMapper sysLoginUserMapper;

    /**
     * 根据用户名查询用户信息  如果用户存在查询权限
     * 用户类型：
     *    互联网用户：
     *    后台用户：
     *  为了区分用户类型，此时需要发送请求的时候携带一个标识
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取请求头中登录标识
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String type = request.getHeader(AuthConstant.LOGIN_TYPE);
        if(AuthConstant.SYS_USER.equals(type)){//系统用户
            //根据用户名查询用户
            SysLoginUser sysLoginUser = sysLoginUserMapper.selectOne(new LambdaQueryWrapper<SysLoginUser>()
                    .eq(SysLoginUser::getUsername, username.trim())
            );
            if(ObjectUtil.isNotNull(sysLoginUser)){
                //查询用户权限信息
                List<String> permList = sysLoginUserMapper.loadUserPerms(sysLoginUser.getUserId());
                sysLoginUser.setPermList(permList);
            }
            return sysLoginUser;
        }else {//互联网用户
            return null;
        }

    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("1"));
    }
}
